package data

import (
	"context"
	"fmt"

	"hellomall/internal/biz"

	"github.com/go-kratos/kratos/v2/log"
	"github.com/pkg/errors"
	v3 "go.etcd.io/etcd/client/v3"
	"go.etcd.io/etcd/client/v3/concurrency"
)

var a int = 0
var lockerName = "mallLocker"

type greeterRepo struct {
	data *Data
	log  *log.Helper

	etcdClient *v3.Client // 可实现waitLock & tryLock
}

// NewGreeterRepo .
func NewGreeterRepo(data *Data, logger log.Logger, etcdCli *v3.Client) biz.GreeterRepo {
	return &greeterRepo{
		data:       data,
		log:        log.NewHelper(logger),
		etcdClient: etcdCli,
	}
}

func (r *greeterRepo) Save(ctx context.Context, g *biz.Greeter) (*biz.Greeter, error) {
	return g, nil
}

func (r *greeterRepo) Update(ctx context.Context, g *biz.Greeter) (*biz.Greeter, error) {
	return g, nil
}

func (r *greeterRepo) FindByID(context.Context, int64) (*biz.Greeter, error) {
	return nil, nil
}

func (r *greeterRepo) ListByHello(context.Context, string) ([]*biz.Greeter, error) {
	return nil, nil
}

func (r *greeterRepo) ListAll(context.Context) ([]*biz.Greeter, error) {
	return nil, nil
}

func (r *greeterRepo) EditMall(id uint64, count int32) error {
	// 这里的业务逻辑需要加分布式锁处理
	// 1、增减库存
	// 2、发送message
	// 3、构建返回结果

	session, errSession := concurrency.NewSession(r.etcdClient)
	if errSession != nil {
		return errors.Errorf("etcdSessionError", errSession)
	}

	locker := concurrency.NewLocker(session, lockerName)
	locker.Lock()
	a += 1
	fmt.Println("current a: ", a)

	locker.Unlock()

	return nil
}
